/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import datamodel.SystemUser;
import ejb.UserManager;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author eXtreme
 */
@ManagedBean(name = "login")
@SessionScoped
public class LoginBean implements Serializable {

    @EJB
    private UserManager um;
    private SystemUser currentUser;
    private boolean welcome = true;
    
    /**
     * Creates a new instance of LoginBean
     */
    public LoginBean() {
    }

    public boolean isLoggedSystemCustomer() {
        return FacesContext.getCurrentInstance().getExternalContext().isUserInRole("SystemCustomer");
    }

    public boolean isLoggedSystemAdmin() {
        return FacesContext.getCurrentInstance().getExternalContext().isUserInRole("SystemAdmin");
    }

    public SystemUser getLoggedUser() {
        if (currentUser == null) {
            loadUser();
        }
        if(welcome){
            welcome=false;
            MessagesController.addInfo("Úspěšné přihlášení uživatele - " + currentUser);
        }
        return currentUser;
    }

    private void loadUser() {
        String name = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
        currentUser = um.getUserByName(name);
    }

    public String logout() {
        System.out.println(">> ODHLASUJI - " + currentUser);
        HttpSession sess = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        sess.invalidate();
        return "login?faces-redirect=true";
    }
}